﻿/**************************************************************
 *
 * 唯一标识：a8ea7f6a-4dd7-4dc5-af17-6c3b0c1e3998
 * 命名空间：Sgr.Cap
 * 创建时间：2024/7/22 15:14:07
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

//using DotNetCore.CAP;
//using DotNetCore.CAP.Filter;
//using DotNetCore.CAP.Messages;
//using Microsoft.EntityFrameworkCore.Storage;
//using Sgr.EntityFrameworkCore;
//using Sgr.Exceptions;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;

//namespace Sgr.Cap
//{
//    /// <summary>
//    /// 实现事务及异常处理(幂等)
//    /// </summary>
//    public class SgrCapFilter : SubscribeFilter
//    {
//        private readonly SgrDbContext _dbContext;
//        private IDbContextTransaction? _transaction;

//        public SgrCapFilter(SgrDbContext dbContext)
//        {
//            _dbContext = dbContext;
//        }

//        /// <summary>
//        /// 执行前
//        /// </summary>
//        /// <param name="context"></param>
//        /// <returns></returns>
//        public override async Task OnSubscribeExecutingAsync(ExecutingContext context)
//        {
//            _transaction = await _dbContext.BeginTransactionAsync() ?? throw new BusinessException("消费消息前，开发数据库事务失败...");
//            await base.OnSubscribeExecutingAsync(context);
//        }

//        /// <summary>
//        /// 执行后
//        /// </summary>
//        /// <param name="context"></param>
//        /// <returns></returns>
//        public override async Task OnSubscribeExecutedAsync(ExecutedContext context)
//        {
//            await base.OnSubscribeExecutedAsync(context);

//            if (_transaction != null)
//                await _dbContext.CommitTransactionAsync(_transaction!);
//        }

//        /// <summary>
//        /// 执行异常时
//        /// </summary>
//        /// <param name="context"></param>
//        /// <returns></returns>
//        public override async Task OnSubscribeExceptionAsync(ExceptionContext context)
//        {
//            await base.OnSubscribeExceptionAsync(context);

//            if (_transaction != null)
//                _dbContext.RollbackTransaction();

//            //context.DeliverMessage.Headers.MessageExceptionRetry();
//        }
//    }
//}